package com.springboot.jwt.config;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.springboot.jwt.common.Result;
import com.springboot.jwt.common.ResultUtils;
import com.springboot.jwt.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: Jyf
 * @Date: 2020/12/17 10:30
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    public Result bizExceptionHandler(BizException e) {
        log.error("bizExceptionHandler: " + e.getErrorMsg());
        return ResultUtils.genFailResult(e.getErrorMsg());
    }

    @ExceptionHandler(value = BindException.class)
    public Result BindException(BindException e) {
        log.error("BindException: {}", e.getFieldError().getDefaultMessage());
        return ResultUtils.genFailResult(e.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = AuthenticationException.class)
    public Result AuthenticationException(AuthenticationException e) {
        log.error("AuthenticationException:{}", e.getMessage());
        return ResultUtils.genFailResult(e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public Result handle401(ShiroException e) {
        log.error("ShiroException:{}", e.getMessage());
        return ResultUtils.genFailResult(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result globalException(Throwable ex) {
        log.error("服务器异常{}", ex.getMessage());
        return ResultUtils.genFailResult("服务器异常:" + ex.getMessage());
    }
}
